package com.kulian.Signalling.system.service.impl.socket.handler;

import com.kulian.Signalling.system.mode.socket.SignalingMessage;
import com.kulian.Signalling.system.service.impl.socket.MessageSender;
import com.kulian.Signalling.system.service.impl.socket.RoomManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class MediaMessageHandler {
    private final MessageSender messageSender;
    private final RoomManager roomManager;

    public void forwardMediaMessage(String from, SignalingMessage message) {
        if (message.getTo() == null || message.getTo().isEmpty()) {
            messageSender.sendError(from, "Missing recipient");
            return;
        }

        // Verify both users are in the same room
        String fromRoom = roomManager.getUserRoom(from);
        String toRoom = roomManager.getUserRoom(message.getTo());
        
        if (fromRoom == null || !fromRoom.equals(toRoom)) {
            messageSender.sendError(from, "Recipient not in same room");
            return;
        }

        messageSender.sendToUser(message.getTo(), message);
        log.debug("Media message forwarded [{} -> {}] type: {}", 
            from, message.getTo(), message.getType());
    }
}
